package cn.enjoyedu.nettybasic.serializable.msgpack2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.unix.Errors;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import javax.sound.sampled.Port;
import java.net.InetSocketAddress;

public class ServerMsgPackEcho {
    public static final int PORT=9995;

    public static void main(String[] args) throws InterruptedException {
        ServerMsgPackEcho serverMsgPackEcho=new ServerMsgPackEcho();
        System.out.println("服务器即将启动");
        serverMsgPackEcho.start();
    }

    private void start() throws InterruptedException {
        EventLoopGroup group=new NioEventLoopGroup();/*线程组*/
        try{
        ServerBootstrap b=new ServerBootstrap();
        b.group(group)
                .channel(NioServerSocketChannel.class)/*指定NIO进行网络传输*/
        .localAddress(new InetSocketAddress(PORT))/*指定服务监听端口*/
        /*服务端每接收一个连接请求，就会新启一个SOCKET通信，也就是channel,
        所以下面的这段代码作用是为了这个子channel增加handle*/
        .childHandler(new ChannelInitializerImp());
        ChannelFuture f=b.bind().sync();/*异步绑定服务器，sync（）会阻塞到完成*/
        System.out.println("服务器启动完成，等待客户端连接和数。。。。。。");
        f.channel().closeFuture().sync();/*阻塞到服务器的channel关闭*/
        }finally {
            group.shutdownGracefully().sync();/*关闭线程组*/

        }
    }
    private static class ChannelInitializerImp extends ChannelInitializer<Channel>{
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535,
                    0,2,0,2));
            ch.pipeline().addLast(new MsgPackDecoder());
            ch.pipeline().addLast(new MsgPackServerHandler());
        }
    }
}
